import ProTable from '@ant-design/pro-table';
import { Form } from '@ant-design/compatible';
import { Button, message, Icon, DatePicker, Modal, Input } from 'antd';
import React, { useState, useRef, useEffect, useCallback } from 'react';
import '@ant-design/compatible/assets/index.css';
import styles from './index.less';
import { queryMsmTable, sendAgain, exportFile} from './service';

import moment from 'moment';
import AuthComponent from '@/components/Authorized/AuthComponent';

const { confirm } = Modal
let hiddenData = null

const TableList = () => {

  // 切换清空搜索
  useEffect(() => {
    hiddenData = null
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])
  // 计算高度
  const [height, controlH] = useState(300);
  const [isCollapse, controlC] = useState(true);
  useEffect(() => {
    if (isCollapse) {
      controlH(document.body.clientHeight - 366.5);
    } else {
      controlH(document.body.clientHeight - 486.5);
    }
  }, [isCollapse])


  const [selectedRowKeys, handleSelectedRowKeys] = useState([]) // 勾选索引
  const [selectedRows, handleSelectedRows] = useState([]) // 勾选列

  const actionRef = useRef();
  const ref = useRef();

  const [inited, setInited] = useState(true)

  const [searchParams, setSearchParams] = useState('')

  const [exportFlag, handleExportFlag] = useState('')

    const formatFlightNo = (val) => {
      if (!val) {
        return '';
      } else if (val.length < 3 || /^\D/.test(val)) {
        return ''.toUpperCase.call(val);
      } else if (/^\d{2}/.test(val)) {
        return `3U${val}`;
      } else {
        return val;
      }
    }
  /**
   * 导出
   */
  const handleExport = () => {
    if (!exportFlag){
      message.error('表格数据为空')
      return false
    }
    const hide = message.loading('正在导出');
    let res = exportFile(searchParams).then(res=>{
      let blob = new Blob([res], {
        type: 'application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      })
      let elink = document.createElement('a')
      elink.style.display = 'none'
      elink.href = URL.createObjectURL(blob)
      document.body.appendChild(elink)
      elink.click()
      document.body.removeChild(elink)
      hide();
      message.success('导出成功');
    }).catch(err => {
      console.log(err)
    });
  }

  /**
   * 重新发送
   */
  const handleSendAgain = async (selectedRows) => {
    console.log(selectedRows.map(row => row.id).toString())
    try {
      await sendAgain({
        ids: selectedRows.map(row => row.id).toString(),
      });
      message.success('发送成功');
      return true;
    } catch (error) {
      message.error('发送失败，请重试！');
      return false;
    }
  }

  // 搜索
  const beforeSearchSubmit = useCallback(params =>{
    if (!isCollapse) {
      setSearchParams(params)
      return params
    } else {
      if (event.target.querySelector('span') && event.target.querySelector('span').innerText === '查 询') {
        if (Object.keys(params).indexOf('flightDateBegin') === -1) {
          params.flightDateBegin = ''
        }
        if (Object.keys(params).indexOf('flightDateEnd') === -1) {
          params.flightDateEnd = ''
        }

        setSearchParams({...hiddenData, ...params})
        return { ...hiddenData, ...params}
        
      } else if (event.target.querySelector('span') && event.target.querySelector('span').innerText === '重 置') {
        ref.current.setFieldsValue({
          flightDateBegin: moment(),
          flightDateEnd: moment()
        })
        hiddenData = null
        setSearchParams(params)
        return params
      }
    }
  }, [isCollapse]);

  const columns = [
    {
      title: '类型',
      dataIndex: 'smsType',
      width: 100,
      filters: [
        {text: '代领审核', value: '1'},
        {text: '行李审核', value: '2'},
        {text: '超售审核', value: '3'}
      ],
      valueEnum:{
        1: '代领审核',
        2: '行李审核',
        3: '超售审核',
        '': '全部'
      },
    },
    {
      title: '航班号',
      dataIndex: 'flightNo',
      width:90,
      order: 6,
      renderFormItem: (_, { type, defaultRender, ...rest }) => {
        return <Input 
          {...rest}
          onChange= {e => {
            e.target.value = formatFlightNo(e.target.value);
            rest.onChange(e.target.value)
          }}
          allowClear maxLength={6} placeholder="3U" />;
      }
    },
    {
      title: '航班日期',
      width:160,
      dataIndex: 'flightDate',
      hideInSearch: true
    },
    {
      title: '航班开始日期',
      hideInTable: true,
      dataIndex: 'flightDateBegin',
      order: 8,
      renderFormItem: (_, { ...rest }) => {
        const format = 'YYYY-MM-DD';
        return (
          <DatePicker
            style={{width: '100%'}}
            format={format}
            {...rest}
          />
        );
      },
    },
    {
      title: '航班结束日期',
      hideInTable: true,
      order: 7,
      dataIndex: 'flightDateEnd',
      renderFormItem: (_, { ...rest }) => {
        const format = 'YYYY-MM-DD';
        return (
          <DatePicker
            style={{width: '100%'}}
            format={format}
            {...rest}
          />
        );
      },
    },
    {
      title: '短信内容',
      dataIndex: 'msg',
      hideInSearch: true,
      ellipsis: true,
      width: 200
    },
    {
      title: '接收号码',
      dataIndex: 'mobile',
      width: 160,
      order: 3
    },
    {
      title: '发送状态',
      dataIndex: 'sendState',
      width:120,
      filters: [
        {text: '成功', value: "0"},
        {text: '失败', value: "1"}
      ],
      valueEnum: {
        0: {
          text: '成功',
          status: 'Success',
        },
        1: {
          text: '失败',
          status: 'Error',
        },
        '': {
          text: '全部'
        }
      },
    },
    {
      title: '发送人',
      dataIndex: 'sender',
      hideInSearch: true,
      width: 90,
    },
    {
      title: '发送时间',
      dataIndex: 'sendTime',
      width: 180,
      value: 'dateTime',
      hideInSearch: true,
    },
    {
      title: '发送开始时间',
      hideInTable: true,
      dataIndex: 'sendTimeBegin',
      order: 5,
      renderFormItem: (_, { ...rest }) => {
        const format = 'YYYY-MM-DD HH:mm:ss';
        return (
          <DatePicker
            showTime
            style={{width: '100%'}}
            format={format}
            {...rest}
          />
        );
      },
    },
    {
      title: '发送结束时间',
      hideInTable: true,
      dataIndex: 'sendTimeEnd',
      order: 4,
      renderFormItem: (_, { ...rest }) => {
        const format = 'YYYY-MM-DD HH:mm:ss';
        return (
          <DatePicker
            format={format}
            style={{width: '100%'}}
            showTime
            {...rest}
          />
        );
      },
    },
  ];

  const tableSelectChange = (selectedRowKeys, selectedRows) =>{
    handleSelectedRowKeys(selectedRowKeys)
    handleSelectedRows(selectedRows)
  }

  const rowSelection = {
    selectedRowKeys,
    onChange: tableSelectChange,
    getCheckboxProps: record => ({
      disabled: record.sendState === '0', // Column configuration not to be checked
    }),
  };


  return (
    <div>
      <ProTable
        className={`${styles.messageTable} rest-pro-table-form-compact ${isCollapse?'':'collapse'}`}
        formRef={ref}
        options={{density: false,fullScreen:true, reload:false, setting:true}}
        scroll={{ x: 1300, y:height }}
        size='small'
        search={{
          onCollapse:val => {
            controlC(val);
            if (!val && hiddenData) {
              ref.current.setFieldsValue({
                sendState:hiddenData.sendState,
                flightNo: hiddenData.flightNo,
                smsType: hiddenData.smsType,
                mobile: hiddenData.mobile,
                sendTimeBegin: hiddenData.sendTimeBegin,
                sendTimeEnd: hiddenData.sendTimeEnd,
              })
            } else {
              hiddenData = ref.current.getFieldsValue()
            }
          }
        }}
        headerTitle="短信发送列表"
        actionRef={actionRef}
        rowKey="id"
        rowSelection={
          (
          AuthComponent.getAuth('message.index.sendAgain'))
          ? rowSelection
          : false
        }
        toolBarRender={(action, { selectedRows }) => [
          <AuthComponent authCode="message.index.sendAgain">
            <Button icon='mail' type="primary" onClick={() => {
              if (selectedRows.length === 0) {
                message.error("请选择发送的条目")
              } else {
                confirm({
                  title: '提示',
                  content: '确认操作后，将为该号码再次发送短信，你还要继续吗？',
                  cancelText: '取消',
                  okText: '确认',
                  onOk: async () => {
                    const result = await handleSendAgain(selectedRows)
                    if(result){
                      actionRef.current.reload();
                      handleSelectedRows([])
                      handleSelectedRowKeys([])
                    }
                  }
                })
              }
            }}>
              重新发送
            </Button>
          </AuthComponent>,
          <AuthComponent authCode="message.index.export">
            <Button icon="download" type="primary" onClick={handleExport}>
              导出
            </Button>
          </AuthComponent>
        ]}
        pagination={{
          showSizeChanger: true,
          showTotal: (total, range) => `${range[0]}-${range[1]} 共 ${total} 项`
        }}
        columns={columns}
        beforeSearchSubmit={beforeSearchSubmit}
        postData={data => {
          if (data.length === 0) {
            handleExportFlag(false)
          } else {
            handleExportFlag(true)
          }
          return data
        }}
        request={params => {
          if (!params['flightDateBegin'] && !params['flightDateEnd'] && inited) {
            setInited(false)
            params['flightDateBegin'] = moment().format('YYYY-MM-DD 00:00:00');
            params['flightDateEnd'] = moment().format('YYYY-MM-DD 23:59:59');
            ref.current.setFieldsValue({
              flightDateBegin: moment(),
              flightDateEnd: moment()
            })
          } else {
            params['flightDateBegin'] = params.flightDateBegin ? params.flightDateBegin.format('YYYY-MM-DD 00:00:00') : '';
            params['flightDateEnd'] = params.flightDateEnd ? params.flightDateEnd.format('YYYY-MM-DD 23:59:59') : '';
          }

          if (!params.sendTimeBegin) {
            ref.current.setFieldsValue({
              sendTimeBegin: ''
            })
          } else {
            params['sendTimeBegin'] = params.sendTimeBegin ? params.sendTimeBegin.format('YYYY-MM-DD HH:mm:ss') : '';
          }
          if (!params.sendTimeEnd) {
            ref.current.setFieldsValue({
              sendTimeEnd: ''
            })
          } else {
            params['sendTimeEnd'] = params.sendTimeEnd ? params.sendTimeEnd.format('YYYY-MM-DD HH:mm:ss') : '';
          }

          if (!params['sendState']) {
            ref.current.setFieldsValue({
              sendState: ''
            })
          }
          if (!params['mobile']) {
            ref.current.setFieldsValue({
              mobile: ''
            })
          }
          if (!params['flightNo']) {
            ref.current.setFieldsValue({
              flightNo: ''
            })
          }
          if (!params['sendTimeBegin']) {
          }
          
          setSearchParams(params)
          return queryMsmTable(params)
        }}
      />
    </div>
  );
};

export default Form.create()(TableList);
